import Axios from 'axios'
import router, { getDynamicRoutes } from '@/router'

const user = {
    state: {
        user: null,
    },
    getters: {
        user: state => state.user,
    },
    mutations: {
        SET_USER(state, data) {
            state.user = data
        },
    },
    actions: {
        user_login({ commit }, data) {
            return new Promise((resolve, reject) => {
                Axios
                    .post('/user/login', data)
                    .then(res => {
                        if (res.code === 200 && res.data.role === 0) {
                            commit('SET_USER', res.data)
                            localStorage.setItem("higame-token", res.token)
                            const routes = getDynamicRoutes(res.data.role)
                            router.addRoutes(routes)
                        } else if (res.code === 200 && res.data.role != 0) {
                            res.code = 204;
                            res.msg = "只能管理员登录！";
                        }
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        user_logout({ commit }) {
            commit('SET_USER', null)
            localStorage.removeItem("higame-token")
        },
        user_check({ commit }) {
            return new Promise((resolve, reject) => {
                Axios
                    .post('/user/check', {})
                    .then(res => {
                        if (res.code === 200) {
                            commit('SET_USER', res.data)
                            localStorage.setItem("higame-token", res.token)
                            const routes = getDynamicRoutes(res.data.role)
                            router.addRoutes(routes)
                        } else {
                            commit('SET_USER', null)
                        }
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        }
    }
}
export default user